package ZJX_net

import (
	"TCP-sever/interface"
	"TCP-sever/utils"
	"bytes"
	"encoding/binary"
	"errors"
	"fmt"
)

type DataPack struct {
}

func NewDataPack() DataPack {
	return DataPack{}
}

//获取包头的长度
func (d *DataPack) GetHeadLen() uint32 {
	//datalen uint32(4字节) + ID uint32(4字节)
	return 8
}

//使用TLV协议封装
func (d *DataPack) Pack(msg ZJX_interface.IMessage) ([]byte, error) {
	//创建一个Buff，用来动态操作二进制数组
	byteBuff := bytes.NewBuffer([]byte{})

	//使用binary工具类向Buff里写入内容
	if err := binary.Write(byteBuff, binary.LittleEndian, msg.GetDataLen()); err != nil {
		return nil, err
	}
	if err := binary.Write(byteBuff, binary.LittleEndian, msg.GetId()); err != nil {
		return nil, err
	}
	if err := binary.Write(byteBuff, binary.LittleEndian, msg.GetData()); err != nil {
		return nil, err
	}

	//将写好了的Buff转化为二进制数组并返回
	return byteBuff.Bytes(), nil
}

//使用TLV协议拆包
func (d *DataPack) UnPack(byteData []byte) (ZJX_interface.IMessage, error) {
	//创建一个从输入二进制数据的ioReader
	byteBuff := bytes.NewReader(byteData)
	msg := &Message{}
	//读dataLen
	//只解压head信息
	if err := binary.Read(byteBuff, binary.LittleEndian, &msg.DataLen); err != nil {
		fmt.Println("set len err", err)
		return nil, err
	}

	//读ID
	if err := binary.Read(byteBuff, binary.LittleEndian, &msg.Id); err != nil {
		fmt.Println("set id err", err)
		return nil, err
	}

	//判断dataLen是否超出了设置的最大长度
	if utils.GlobalObject.MaxPackageSize > 0 && msg.DataLen > utils.GlobalObject.MaxPackageSize {
		return nil, errors.New("too Large msg data")
	}

	return msg, nil
}
